<template>
	<view class="box" v-if="info && circleInfo">
		<HeaderBar title="设置名片样式" :opacity="opacity" />
		<image :src="getImg()" mode="widthFix" class="bg1"></image>
		<!-- 	<view class="hb-img">
			<l-painter :board="poster" style="width: 100%;" ref="painterRef"/>
		</view> -->
		<view class="hb-img">
			<card ref="cardRef" />
			<view class="lh" v-if="circleInfo.circle_config && circleInfo.circle_config.card_logo">
				<image :src="circleInfo.circle_config.card_logo" mode="heightFix"></image>
			</view>
			<view class="real_name" v-if="circleInfo.real_name === 1">
				<image :src="ossUrl + `/static/image/vip/${circleInfo.vip === 1 ? 2 : 1}.png`"
					v-if="!is_vip && circleInfo.vip === 1" mode="widthFix"></image>
				实名
			</view>
		</view>
		<view class="title">选择布局</view>
		<view class="scroll">
			<view :class="it.checked ? 'scroll-item-ac scroll-item' : 'scroll-item'"
				v-for="(it,index) in info.business_card_layout" :key="it.id" @click="setBusinessCard(it,index)">
				<view class="scroll-item-img">
					<image :src="it.cover_img" mode=""></image>
				</view>
				<view class="scroll-item-select" v-if="it.checked">
					<image :src="ossUrl +  '/static/image/s3.png'" mode=""></image>
				</view>
				
				<image :src="ossUrl + `/static/image/vip/5.png`" class="card-vip" mode="widthFix"
					v-if="it.vip_status == 1"></image>
				
				<image :src="ossUrl + `/static/image/vip/6.png`" class="card-vip" mode="widthFix"
					v-if="it.user_id"></image>	
			</view>
		</view>
		<view class="line"></view>
		<view class="title">选择背景</view>
		<view class="scroll">
			<view :class="it.checked ? 'scroll-item-ac scroll-item' : 'scroll-item'"
				v-for="(it,index) in info.business_card_background" :key="it.id" @click="setBackgroundCard(it,index)">
				<view class="scroll-item-img">
					<image :src="it.img" mode=""></image>
				</view>
				<view class="scroll-item-select" v-if="it.checked">
					<image :src="ossUrl +  '/static/image/s3.png'" mode=""></image>
				</view>
				<image :src="ossUrl + `/static/image/vip/5.png`" class="card-vip" mode="widthFix"
					v-if="it.vip_status == 1"></image>
			</view>
		</view>
		<view class="title" v-if="getChecked()">形象照</view>
		<view class="upload" v-if="getChecked()">
			<view class="upload-img" @click="upload">
				<image :src="cropperUrl ? cropperUrl : ossUrl + '/static/image/组149.png'" mode=""></image>
			</view>
			<view class="upload-r">
				<view class="upload-r-tx" style="width: 400rpx;">切换样式后，如果尺寸不对，请重新上传。</view>
				<view class="upload-r-tx">大小10M内</view>
				<view class="upload-r-btn" v-if="cropperUrl" @click="upload">重新上传</view>
			</view>
		</view>
		<view class="btns" @click="submit">保存</view>
		<l-painter :board="template" style="width: 100%;" ref="painterRef" custom-style="position: fixed; left: 200%" />
		<!-- 会员弹窗 -->
		<MemberPopupVue ref="MemberPopupVueRef" @reload="reload"/>
	</view>
</template>

<script>
	import MemberPopupVue from '@/components/memberPopup/memberPopup.vue'
	import {
		InformationBusinessCardStyle,
		InformationStyleSaving,
		InformationUserInfo,
		InformationShareStylesSaving,
		InformationUserBusinessCardHeadData,
		InformationBusinessCard
	} from '@/common/http/api.js'
	// import {
	// 	this.getTemplateCard
	// } from './config.js'
	import {
		ossUpload,
		ossDel
	} from '@/common/oss.js'
	import card from '@/components/card/card.vue'
	import HeaderBar from "@/components/header/header.vue";
	export default {
		components: {
			card,
			HeaderBar,
			MemberPopupVue
		},
		data() {
			return {
				path: '',
				poster: {},
				info: '',
				business_card_id: '',
				opacity: 0,
				userInfo: '',
				template: {},
				cardStyleInfo: '',
				imgWid: [],
				circleInfo: ''
			};
		},
		onLoad(e) {
			InformationBusinessCard().then(d => {
				this.circleInfo = d.data
				InformationUserInfo().then(res => {
					this.userInfo = res.data
					this.business_card_id = e.id
					//清空裁剪的图片
					this.$store.commit('setCropperUrl', '')
					InformationBusinessCardStyle({
						business_card_id: e.id,
						circle_id: d.data.circle_id
					}).then(res => {
						this.info = res.data

						res.data.business_card_background.forEach((i, index) => {
							i.checked = false

							if (this.isValid(this.info.default)) {
								if (i.id == this.info.default.background_id) {
									i.checked = true
								}
							} else {
								if (index === 0) {
									i.checked = true
								}
							}
						})
						res.data.business_card_layout.forEach((i, index) => {
							i.checked = false
							if (this.isValid(this.info.default)) {
								if (i.id == this.info.default.style_id) {
									i.checked = true
								}
							} else {
								if (index === 0) {
									i.checked = true
								}
							}
						})

						if (!this.isValid(this.info.default)) {
							//第一次
							this.getTemplateCard(this.info.business_card_layout[0], this.info.user,
								this.cropperUrl, this.userInfo)
						} else {

							// this.this.cropperUrl = this.info.user_img
							this.$store.commit('setCropperUrl', this.info.default.user_img)

							//编辑
							if (this.info.business_card_layout.some(i => i.id == this.info.default
									.style_id)) {
								let d = this.info.business_card_layout.find(i => i.id == this.info
									.default.style_id)
								console.log('d=>', d)
								this.getTemplateCard(d, this.info.user, this.cropperUrl, this
									.userInfo)
							} else {
								this.getTemplateCard(this.info.business_card_layout[0], this.info
									.user, this.cropperUrl, this.userInfo)
							}
						}
						this.setWH()
					})
				})
			})


		},
		computed: {
			// imgWid(){
			// 	let info = {}
			// 	try{
			// 		info = this.info.business_card_layout.find(i=>i.checked)
			// 	}catch(e){
			// 		//TODO handle the exception
			// 	}

			// 	let w = Number(info.wide || 0)
			// 	let h = Number(info.tall || 0)

			// 	console.log('宽高',info,[w,h])
			// 	return [w,h]
			// },
			cropperUrl() {
				return this.$store.state.cropperUrl
			},


		},
		watch: {
			cropperUrl: {
				handler(val) {
					console.log('val', val)
					let info = this.info.business_card_layout.find(i => i.checked)
					this.getTemplateCard(info, this.info.user, val, this.userInfo)
				},
				deep: true
			},
			// info:{
			// 	handler(val){
			// 		let info = {}
			// 		try{
			// 			info = this.info.business_card_layout.find(i=>i.checked)
			// 		}catch(e){
			// 			//TODO handle the exception
			// 		}

			// 		let w = Number(info.wide || 0)
			// 		let h = Number(info.tall || 0)

			// 		console.log('宽高',info,[w,h])
			// 		this.imgWid = [w,h]
			// 	},
			// 	deep: true
			// }
		},
		onPageScroll(e) {
			const scrollTop = e.scrollTop
			// 计算透明度值
			this.opacity = Math.min(scrollTop / 100, 1);
		},
		methods: {
			reload(){
				InformationUserInfo().then(res=>{
					this.userInfo = res.data
				})
			},
			getChecked() {
				let status = true
				try {
					status = this.info.business_card_layout.find(i => i.checked).type != 3
				} catch (e) {

				}
				return status
			},
			getTemplateCard(info, user, cropperUrl, userInfo) {

				this.$nextTick(() => {
					this.$refs.cardRef.show({...info,lng: this.circleInfo.lng, lat: this.circleInfo.lat, address: this.circleInfo.address }, user, cropperUrl, userInfo)
				})
			},
			getCurrentStyle() {

			},
			getImg() {
				let img = ''

				if (this.info.business_card_background.some(i => i.checked)) {
					img = this.info.business_card_background.find(i => i.checked).img
				}
				return img
			},
			setWH() {
				let info = {}
				try {
					info = this.info.business_card_layout.find(i => i.checked)
				} catch (e) {
					//TODO handle the exception
				}

				let w = Number(info.wide || 0)
				let h = Number(info.tall || 0)

				console.log('宽高', info, [w, h])
				this.imgWid = [w, h]
			},
			setBusinessCard(it, index) {
				if (it.vip_status == 1 && this.userInfo.vip === 0) {
					this.$refs.MemberPopupVueRef.show()
					return
				}
				this.info.business_card_layout.forEach((i, index) => {
					i.checked = false
				})
				this.info.business_card_layout[index].checked = true
				this.getTemplateCard(it, this.info.user, this.cropperUrl, this.userInfo)
				this.$forceUpdate()

				this.setWH()

			},
			setBackgroundCard(it, index) {
				if (it.vip_status == 1 && this.userInfo.vip === 0) {
					this.$u.toast('请购买vip！')
					return
				}
				this.info.business_card_background.forEach((i, index) => {
					i.checked = false
				})
				this.info.business_card_background[index].checked = true
				this.$forceUpdate()
			},
			upload() {
				uni.navigateTo({
					url: '/pagesC/clipper/clipper?w=' + this.imgWid[0] + '&h=' + this.imgWid[1] + '&type=1'
				})
			},
			submit() {
				let info = this.info.business_card_layout.find(i => i.checked)
				let background = this.info.business_card_background.find(i => i.checked)
				if (this.getChecked()) {
					if (this.cropperUrl === '') {
						uni.showToast({duration:3000,
							title: '请上传形象照',
							icon: 'none'
						})
						return
					}
				}

				uni.showLoading()
				this.$refs.cardRef.submit().then(data => {
				
					ossUpload(data).then(res => {
						let business_card_img = res.url
						let data = {
							style_id: info.id,
							background_id: background.id,
							user_img: this.cropperUrl,
							business_card_img,
							business_card_id: this.business_card_id
						}
						
						
						console.log('data', data)
						uni.showLoading()
						InformationStyleSaving(data).then(res => {
							// uni.showToast({duration:3000,
							// 	title:'保存成功',
							// 	icon: 'none'
							// })
							// uni.navigateBack()
							InformationUserBusinessCardHeadData({

								business_card_id: this.business_card_id
							}).then(res => {
								this.cardStyleInfo = res.data

								this.template = {
									css: {
										// 根节点若无尺寸，自动获取父级节点
										width: '333rpx',
										height: '266.4rpx'
									},
									views: [
										//底图
										{
											type: 'image',
											src: this.cardStyleInfo.Template_img,
											css: {
												width: '100%',
												height: '100%',
												top: "0",
												right: "0",
												position: "absolute",
												zIndex: '5',
											}
										},
										//名片
										{
											type: 'image',
											src: business_card_img,
											css: {
												width: '333rpx',
												top: "0",
												right: "0",
												position: "absolute",
												zIndex: '4',
											}
										}
									]
								}
								this.$nextTick(() => {
									this.setShareCardHttp()
								})
							})

						})
					}).catch(err => {
						uni.showToast({duration:3000,
							title: '上传失败！',
							icon: 'none'
						})
					})
				}).catch(err => {
					console.log('err', err)
					uni.showToast({duration:3000,
						title: "未能生成，请重新保存!",
						icon: 'none'
					})
				})
			},
			async setShareCardHttp() {
				this.$refs.painterRef.canvasToTempFilePathSync({
					fileType: "jpg",
					// 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
					pathType: 'url',
					quality: 1,
					success: (res) => {
						console.log(res.tempFilePath);

						// 非H5 保存到相册
						// H5 提示用户长按图另存
						ossUpload(res.tempFilePath).then(res => {
							let business_card_img = res.url
							let data = {
								share_id: this.cardStyleInfo.share_id,
								share_img: business_card_img,
								business_card_id: this.cardStyleInfo.business_card_id,
								intercept: this.cardStyleInfo.intercept
							}
							console.log('data', data)
							InformationShareStylesSaving(data).then(res => {
								uni.showToast({duration:3000,
									title: '保存成功',
									icon: 'none'
								})
								setTimeout(() => {
									this.$store.dispatch('getShare')
									this.$store.commit('setIsRefresh', true)
									uni.navigateBack()
								}, 1500)


							}).catch(err => {
								uni.hideLoading()
							})
						}).catch(err => {
							uni.showToast({duration:3000,
								title: '上传失败！',
								icon: 'none'
							})
						})
					},
				});
			}
		}
	}
</script>

<style lang="scss">
	.box {
		padding: 30rpx 0;
	}

	image {
		width: 100%;
		height: 100%;
	}

	.hb-img {
		width: 690rpx;
		// height: 360rpx;
		// background: #FFFFFF;
		// box-shadow: 0rpx 10rpx 8rpx 0rpx rgba(14, 67, 44, 0.15);
		// border-radius: 30rpx;
		margin: 0 auto;
		margin-bottom: 45rpx;
		position: relative;

		.lh {
			position: absolute;
			top: -90rpx;
			left: 0;
			height: 80rpx;
			z-index: 8;

			image {
				height: 100%;
			}
		}
		.real_name {
			// width: 83rpx;
			padding: 0 15rpx;
			height: 35rpx;
			background: #D2FCEC;
			border-radius: 5rpx;
			font-family: PingFang SC;
			font-weight: 400;
			font-size: 22rpx;
			color: #23B97F;
			position: absolute;
			right: 20rpx;
			top: 20rpx;
			z-index: 99;
			display: flex;
			align-items: center;
			justify-content: center;
		
			image {
				width: 20rpx;
				margin-right: 6rpx;
			}
		}
	}

	.title {
		font-family: PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #131313;
		margin-bottom: 32rpx;
		box-sizing: border-box;
		padding-left: 30rpx;
	}

	.scroll {
		width: 100%;
		overflow-x: scroll;
		white-space: nowrap;
		padding-bottom: 90rpx;

		.scroll-item {
			display: inline-block;
			width: 219rpx;
			height: 129rpx;
			position: relative;
			margin-left: 30rpx;

			.scroll-item-img {
				width: 100%;
				height: 100%;
			}

			.scroll-item-select {
				width: 46rpx;
				height: 46rpx;
				position: absolute;
				bottom: -60rpx;
				left: 50%;
				transform: translateX(-50%);
			}
		}

		.scroll-item:last-child {
			margin-right: 30rpx;
		}

		.scroll-item-ac {
			border: 4px solid #12B475;
		}

	}

	.card-vip {
		position: absolute;
		top: 0;
		right: 0;
		z-index: 9999;
		width: 70rpx;
	}

	.line {
		width: 690rpx;
		height: 1rpx;
		background: #E2E2E2;
		margin: 0 auto;
		margin-bottom: 30rpx;
	}

	.upload {
		width: 690rpx;
		margin: 0 auto;
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;

		.upload-img {
			width: 158rpx;
			height: 158rpx;
			margin-right: 14rpx;
		}

		.upload-r {
			.upload-r-tx {
				font-family: PingFang;
				font-weight: 400;
				font-size: 24rpx;
				color: #999999;
				margin-bottom: 19rpx;
			}

			.upload-r-tx:last-child {
				margin-bottom: 36rpx;
			}

			.upload-r-btn {
				width: 156rpx;
				height: 54rpx;
				border-radius: 26rpx;
				border: 1px solid #999999;
				display: flex;
				align-items: center;
				justify-content: center;
				font-family: PingFang;
				font-weight: 400;
				font-size: 24rpx;
				color: #131313;
			}
		}
	}

	.btns {
		width: 578rpx;
		height: 86rpx;
		background: #12B475;
		box-shadow: 0rpx 8rpx 8rpx 0rpx rgba(177, 177, 177, 0.45);
		border-radius: 43rpx;
		font-family: PingFang SC;
		font-weight: 400;
		font-size: 30rpx;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 30rpx auto;
		font-weight: bold;
	}

	.bg1 {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		z-index: -2;
	}
</style>